#!/usr/bin/python
#-*-coding: utf-8 -*-

u"""
Utilitaires variés pour pylot.qtgui
"""

import PyQt4.uic
from PyQt4.QtGui import (QToolBar, QMenu, QAction, QMenuBar, QGroupBox, QIcon,
                         QPalette, QBrush, QColor, QWidget, QToolButton)
from PyQt4.QtCore import (QString)


from pylot.core import (Path, good_level_2, error, hardbook)

__all__ = [u'load_designer_file',
           u'qcolor_to_qstring', u'qstring_to_qcolor',
           u'create_background_palette',
           u'set_qt_widget_text', u'set_qt_widget_texts',
           u'fill', u'get_icon', u'get_named_font']


def get_named_font (name, char_formats):
  u"""
  get font of 'format' called 'name'. If not exists, return 'std' font.
  'format' is an element of formats attribute. see L{GuipyLotManager._createFonts}

  :param name: format name (see self.formats)
  :type name: str

  :return: format font
  :rtype: QFont
  """
  try:
    cformat = char_formats[name]
  except KeyError :
    cformat = char_formats[u'std']
  return cformat.font()

def fill(widget, actions, current_level=u'expert'):
  u"""
  This methods simplify menu and toolbar filling.
  Fill a widget (like menu, toolbars) with given actions.
  action is a list of QAction, QMenu or special keywords.

  Allowed keywords : '-', add a separator

  :param widget: the widget you want to fill
  :type widget: QToolBar, QMenuBar, QMenu
  :param action: list of "actions" (QAction, QMenu, or "-")
  :type action: QAction, QMenu or str
  """
  curlevel = current_level
  supported_qwidgets = (QMenu, QAction, QMenuBar, QToolBar, QToolButton)
  if not issubclass(type(widget), supported_qwidgets) :
    classes = u', '.join([unicode(c) for c in supported_qwidgets])
    raise ValueError, error(tr_(u'widget: %s required, got %s') % (classes, type(widget)))
  widget.clear()

  for action in actions :
    level = u'user'
    if isinstance(action, tuple) :
      if len(action) >= 2 :
        level = action[1]
        action = action[0]
      else :
        pass
    if isinstance(action, unicode) :
      if action.lower() in (u'-',) and good_level_2(curlevel, level) :
        widget.addSeparator()
      elif action.lower() in (u'-',) :
        pass
      else :
        raise NotImplementedError
    elif isinstance(action, QAction) and good_level_2(curlevel, level) :
      widget.addAction(action)
    elif isinstance(action, QMenu) and good_level_2(curlevel, level) :
      widget.addMenu(action)
    elif isinstance(action, QWidget) and good_level_2(curlevel, level) :
      raise ValueError, tr_(u'fill method only support QWidgetAction for widgets')
    else :
      pass

def set_qt_widget_text (widget, text, field=u'text'):
  u"""
  This method recognize widget type and use good method

  :param widget: QWidget you want to translate
  :type widget: QWidget
  :param text: english text
  :type text: unicode
  :param field: what widget text you want to translate, default 'text' fields availables: tooltip, shortcut, text
  :type field: unicode
  """
  if field == u'text' :
    try :
      widget.setText(text)
    except AttributeError :
      if isinstance(widget, (QMenuBar, QMenu, QGroupBox)) :
        widget.setTitle(text)
      elif isinstance(widget, QWidget) :
        widget.setWindowTitle(text)
      else :
        raise AttributeError, error(tr_(u'%s do not support setText" method') % widget)

  elif field == u'tooltip':
    try :
      widget.setToolTip(text)
    except AttributeError :
      raise AttributeError, error(tr_(u'%s do not support "setTooltip" method') % widget)

  elif field == u'shortcut':
    try :
      widget.setShortcut(text)
    except AttributeError :
      raise AttributeError, error(tr_(u'%s do not support "setShortcut" method') % widget)

  elif field == u'whatsthis' :
    try :
      widget.setWhatsThis(text)
    except AttributeError :
      raise AttributeError, error(tr_(u'%s do not support "setWhatsThis" method') % widget)

  else :
    raise ValueError, error(tr_(u'Unknown field %r') % field)

def set_qt_widget_texts (widget_text_list, field=u'text'):
  u"""
  :param widget_trad_list: list of cuple (QWidget, text)
  """
  for couple in widget_text_list :
    widget, text = couple
    set_qt_widget_text(widget, text, field)

def create_background_palette (qcolor):
  bg = QPalette()
  bg.setBrush(QPalette.Active, QPalette.Base, QBrush(qcolor))
  bg.setBrush(QPalette.Inactive, QPalette.Base, QBrush(qcolor))
  return bg

def qcolor_to_qstring (qcolor):
  u"""
  ex: QColor(255, 255, 255) -> QString("255,255,255,255")

  @type qcolor: QColor
  @rtype: QString
  """
  RGBA = [qcolor.red(), qcolor.green(), qcolor.blue(), qcolor.alpha()]
  RGBA = [unicode(c) for c in RGBA]
  return QString(u','.join(RGBA))

def qstring_to_qcolor (qstring):
  u"""
  ex: QString("255,255,255,255") -> QColor(255, 255, 255, 255)

  @type qstring: QString
  @rtype: QColor
  """
  RGBA = unicode(qstring)
  RGBA = [int(c) for c in RGBA.split(u',')]
  return QColor(*RGBA)

def get_icon(filename, additionnal_dirs=[]):
  try :
    from _pylot.defaultconf import hardbook
  except ImportError :
    icon_path = Path(u'pylot', u'share', u'icons', filename)
  else :
    icon_path = hardbook(u'icons', filename)
  if icon_path.isfile() :
    return QIcon(icon_path)
  else :
    for path in additionnal_dirs :
      icon_path = Path(path, filename)
      if icon_path.isfile() :
        return QIcon(icon_path)
    return QIcon(icon_path) # No icon

def load_designer_file (filename, additionnal_dirs=[]) :
  u"""
  Try to load pylot/share/qtdesigner/filename. If loading fails, we suppose we
  are not in root directory. If we are not in sour

  :param filename: the qt-designer ui file name. Ex: options.ui
  :type filename: str

  :return: Qt class (corresponding to filename), Qt type class (type of first value)
  :rtype: couple
  """
  paths = [
    filename,
    hardbook(u'share', u'qtdesigner', filename),
    ] + [Path(directory, filename) for directory in list(additionnal_dirs)]

  for path in paths :
    try :
      UiClass, UiClassType = PyQt4.uic.loadUiType(path)
    except IOError :
      pass
    else :
      return UiClass, UiClassType

  raise IOError, error(tr_(u'%s not found. Please re-install pylot and try again') % filename)

#  try :
#    from _pylot.defaultconf import qtdesigner
#  except ImportError :
#    raise IOError, error(tr_(u'%s not found. Please try again from pylot source directory') % filename)
#  else :
#    try :
#      UiClass, UiClassType = PyQt4.uic.loadUiType(Path(qtdesigner, filename))
#      #print "### load_designer_file : %s" % Path(qtdesigner, filename)
#    except IOError :
#      raise IOError, error(tr_(u'%s not found. Please re-install pylot and try again') % filename)
#    else :
#      return UiClass, UiClassType

if __name__ == u"__main__":
  pass
